﻿using log4net;
using System.Linq;

namespace Sherwood.Content.UpdateServices.Attachments
{
    public class AttachmentSearchDocumentModifier<TAttachmentMeta> : ISearchDocumentModifier
        where TAttachmentMeta : IAttachmentMeta
    {
        private static readonly ILog Log = LogManager.GetLogger(typeof(AttachmentSearchDocumentModifier<TAttachmentMeta>));

        public void Fill(ISearchDocument searchDocument, IRecord record)
        {
            if(Log.IsDebugEnabled)
                Log.DebugFormat("Filling search document for record {0}", record.Id);

            var doc = searchDocument as IAttachmentSearchDocument;
            if (doc != null)
            {
                foreach (var meta in record.Metas.OfType<TAttachmentMeta>())
                {
                    foreach (var attachment in meta.GetAttachments())
                        doc.AddAttachment(attachment.FileName, attachment.TextContent);
                }
            }
            else
                Log.Warn(searchDocument.GetType() + " does not implement IBookSearchDocument");
        }
    }
}